<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="模板名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入模板名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="模板分类" prop="category">
            <el-input
              v-model="queryParams.category"
              placeholder="请输入模板分类"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="价格区间" prop="price">
            <el-input
              v-model="queryParams.price"
              placeholder="请输入价格"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="是否激活" prop="isActive">
            <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable style="width: 100%">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:templates:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:templates:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:templates:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:templates:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 网格卡片布局 -->
    <el-row v-loading="loading" :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="item in templatesList" :key="item.templateId">
        <el-card :body-style="{ padding: '0px' }" class="template-card" shadow="hover">
          <div class="template-selection">
            <el-checkbox @change="(val) => handleSelectionChange([item], val)"></el-checkbox>
          </div>
          <div class="template-image">
            <el-image 
              v-if="item.previewImageUrl" 
              :src="item.previewImageUrl" 
              fit="cover"
              class="template-image-content">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <div v-else class="no-image">
              <i class="el-icon-picture-outline"></i>
            </div>
            <div class="image-overlay">
              <el-button circle icon="el-icon-zoom-in" size="mini" @click="previewImage(item.previewImageUrl)"></el-button>
              <el-button circle icon="el-icon-edit" size="mini" @click="handleUpdate(item)"></el-button>
            </div>
          </div>
          <div class="template-content">
            <div class="template-name">
              {{ item.name }}
              <span class="template-id">ID: {{ item.templateId }}</span>
            </div>
            <div class="template-info">
              <div class="template-category">
                <el-tag size="mini" effect="plain">{{ item.category }}</el-tag>
              </div>
              <div class="template-price">{{ item.price > 0 ? '¥ ' + item.price : '免费' }}</div>
            </div>
            <div class="template-status">
              <el-tag size="mini" :type="item.isActive == 1 ? 'success' : 'info'" effect="dark">{{ item.isActive == 1 ? '激活' : '禁用' }}</el-tag>
            </div>
          </div>
          <div class="template-footer">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(item)"
              v-hasPermi="['system:templates:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(item)"
              v-hasPermi="['system:templates:remove']"
            >删除</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改信笺模板管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="模板分类" prop="category">
          <el-input v-model="form.category" placeholder="请输入模板分类" />
        </el-form-item>
        <el-form-item label="预览图" prop="previewImageUrl">
          <div class="preview-image-container">
            <image-upload v-model="form.previewImageUrl" :limit="1"/>
            <div class="upload-tip">请上传大小不超过5MB的图片文件，支持PNG、JPG、JPEG格式</div>
          </div>
        </el-form-item>
        <el-form-item label="资源URL" prop="digitalAssetUrl">
          <el-input v-model="form.digitalAssetUrl" placeholder="请输入电子资源URL" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.5" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否激活" prop="isActive">
          <el-switch
            v-model="form.isActive"
            active-text="激活"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplates, getTemplates, delTemplates, addTemplates, updateTemplates } from "@/api/system/templates";
import ImageUpload from "@/components/ImageUpload";

export default {
  name: "Templates",
  components: { ImageUpload },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中对象数组
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 信笺模板管理表格数据
      templatesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12, // 调整默认每页显示数量
        name: null,
        description: null,
        category: null,
        type: null,
        previewImageUrl: null,
        digitalAssetUrl: null,
        price: null,
        isActive: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedAt: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询信笺模板管理列表 */
    getList() {
      this.loading = true;
      listTemplates(this.queryParams).then(response => {
        this.templatesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        name: null,
        description: null,
        category: null,
        type: "electronic", // 默认设置为电子类型，但表单中不显示
        previewImageUrl: null,
        digitalAssetUrl: null,
        price: 0,
        isActive: 1,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.beginCreateTime = this.dateRange[0];
        this.queryParams.endCreateTime = this.dateRange[1];
      } else {
        this.queryParams.beginCreateTime = undefined;
        this.queryParams.endCreateTime = undefined;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 处理选择变化
    handleSelectionChange(rows, selected) {
      if (selected) {
        // 添加到选中项
        this.selection.push(...rows);
      } else {
        // 从选中项中移除
        const ids = rows.map(row => row.templateId);
        this.selection = this.selection.filter(item => !ids.includes(item.templateId));
      }
      // 更新ids数组
      this.ids = this.selection.map(item => item.templateId);
      this.single = this.selection.length !== 1;
      this.multiple = !this.selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加信笺模板管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids[0];
      getTemplates(templateId).then(response => {
        this.form = response.data;
        // 确保isActive是数字类型
        if (this.form.isActive !== null && this.form.isActive !== undefined) {
          this.form.isActive = Number(this.form.isActive);
        }
        this.open = true;
        this.title = "修改信笺模板管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.templateId != null) {
            updateTemplates(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplates(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids.join(',');
      this.$modal.confirm('是否确认删除信笺模板管理编号为"' + templateIds + '"的数据项？').then(function() {
        return delTemplates(templateIds);
      }).then(() => {
        this.getList();
        // 清空选择
        this.selection = [];
        this.ids = [];
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/templates/export', {
        ...this.queryParams
      }, `templates_${new Date().getTime()}.xlsx`)
    },
    /** 预览图片 */
    previewImage(url) {
      if (!url) return;
      this.$modal.openImg(url);
    }
  }
};
</script>

<style scoped>
.preview-image-container {
  width: 100%;
}
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
.template-card {
  margin-bottom: 20px;
  position: relative;
  height: 330px;
  transition: all 0.3s ease;
  border-radius: 10px;
  overflow: hidden;
  border: none;
}
.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}
.template-selection {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  opacity: 0.8;
  transition: all 0.3s ease;
}
.template-selection:hover {
  opacity: 1;
}
.template-image {
  height: 180px;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
}
.template-image .el-image {
  width: 100%;
  height: 100%;
  transition: all 0.5s ease;
}
.template-image:hover .el-image {
  transform: scale(1.05);
}
.template-image .no-image {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
}
.template-image .no-image i {
  font-size: 48px;
  color: #c0c4cc;
}
.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  opacity: 0;
  transition: all 0.3s ease;
}
.template-image:hover .image-overlay {
  opacity: 1;
}
.template-content {
  padding: 16px;
  background: white;
}
.template-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
}
.template-id {
  font-size: 12px;
  font-weight: normal;
  color: #909399;
  margin-left: 8px;
}
.template-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.template-category {
  font-size: 14px;
}
.template-price {
  font-size: 14px;
  font-weight: bold;
  color: #f56c6c;
}
.template-status {
  margin-top: 8px;
}
.template-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  text-align: right;
  border-top: 1px solid #f0f2f5;
  background: #fafafa;
}
</style>
